import { onMounted, onUnmounted, ref, type Ref } from "vue"

//获取当前实时时间
export function useCurrentDate() {
  const currentDate = ref<Date>(new Date())
  const updateCurrenDateTimer = ref()

  onMounted(() => {
    updateCurrenDateTimer.value = setInterval(() => {
      currentDate.value = new Date()
    }, 1000)
  })

  onUnmounted(() => {
    if (updateCurrenDateTimer.value) {
      clearInterval(updateCurrenDateTimer.value)
    }
  })

  return { currentDate }
}

export function useElementRect(element: Ref<HTMLElement | undefined>) {

  const setRect = (value: HTMLElement | undefined) => {
    return {
      left: value?.getBoundingClientRect().left || 0,
      right: window.innerWidth - (value?.getBoundingClientRect().right || window.innerWidth),
      top: value?.getBoundingClientRect().top || 0,
      bottom: window.innerHeight - (value?.getBoundingClientRect().bottom || window.innerHeight)
    }
  }

  const onScroll = () => {
    rect.value = setRect(element.value)
  }

  const rect = ref()
  onMounted(() => {
    rect.value = setRect(element.value)
    window.onresize = () => {
      rect.value = setRect(element.value)
    }
    window.addEventListener("scroll", onScroll)
  })

  onUnmounted(() => {
    window.removeEventListener("scroll", onScroll)
  })

  return { rect }
}
